package com.lizhen.core.function.mail;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Mail {
    public static void main(String[] args) {
        String userPswd = System.getenv("user_pswd");
        try {
            InputStream inputStream = new FileInputStream(userPswd);
            Properties properties = new Properties();
            properties.load(inputStream);
            String to = properties.getProperty("qq_email_user");
            String from = properties.getProperty("qq_email_user");
            String user = properties.getProperty("qq_email_user");
            String pswd = properties.getProperty("qq_email_pswd");
            Properties properties2 = new Properties();
            // 设置邮件服务器主机名
            properties2.setProperty("mail.smtp.host", "smtp.qq.com");
            // 发送服务器需要身份验证
            properties2.setProperty("mail.smtp.auth", "true");
            Session session = Session.getInstance(properties2, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(user, pswd);
                }
            });
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject("JavaMail");
            message.setText("Hello, this is an example for to check send email using JavaMailAPI ");
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
